<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<form id="form" action="#">
  <input type="text" placeholder="请输入用户名" name="userName">
  <input type="text" placeholder="请输入电话号" name="tel">
  <input type="password" placeholder="请输入密码" name="password">
  <input type="submit" value="提交">
</form>
<script>
  /**
   * 1. 耦合性太大
   * 2. 多个if违反 开放封闭原则
   * 3. 策略类 + 策略类封装 + 环境类
   * @type {HTMLElement}
   */
  // var registerForm = document.getElementById("registerForm");
  // registerForm.onsubmit = function () {
  //   if (registerForm.userName.value === '') {
  //     alert('用户名不能为空');
  //     return;
  //   }
  //   if (registerForm.password.value.length < 6) {
  //     alert("密码的长度不能小于6位");
  //     return;
  //   }
  //   if (!/(^1[3|5|8][0-9]{9}$)/.test(registerForm.phoneNumber.value)) {
  //     alert("手机号码格式不正确");
  //     return;
  //   }
  // }

  /*策略类*/
  let rules = {
    isNoEmpty(value, errorMsg) {
      if (value === '') {
        return errorMsg
      }
    },
    minLength(value, length, errorMsg) {
      if (value.length < length) {
        return errorMsg;
      }
    },
    mobileFormat(value, errorMsg) {
      if (!/(^1[3|5|8][0-9]{9}$)/.test(value)) {
        return errorMsg;
      }
    }
  };

  /*策略封装类 */
  function Validate() {
    // 添加校验规则
    this.rules = [];
    // 开始校验
  }

  /*调用此函数 添加校验规则*/
  Validate.prototype.addRules = function (dom, rule, errorMsg) {
    let ruleArr = rule.split(':');
    this.rules.push(function () {
      let myRule = ruleArr.shift();
      ruleArr.push(errorMsg);
      return rules[myRule](dom.value, ...ruleArr) // ''
    })
  };

  /*调用此函数 就开始校验*/
  Validate.prototype.execute = function () {
    for (let i = 0; i < this.rules.length; i++) {
      let errorMsg = this.rules[i]();
      if (errorMsg) {
        return errorMsg
      }
    }
  };

  //
  // validator.addRules(registerForm.userName,
  // 'isNoEmpty','用户名不能为空')
  // // validator.addRules(registerForm.userName,'minLength:6','用户名不能为空')
  /* 环境类*/
  function validateFuncs() {
    let validate = new Validate();
    validate.addRules(form.userName, 'isNoEmpty', "用户名不能为空");
    validate.addRules(form.tel, 'mobileFormat', "手机号码格式不正确");
    validate.addRules(form.password, 'minLength:6', "密码的长度不能小于6位");
    return validate.execute()
  }


  form.onsubmit = function () {
    let errorMsg = validateFuncs();
    if (errorMsg) {
      alert(errorMsg);
      return false;
    }
  };
  /* 利用策略模式 校验表单*/

</script>
</body>
</html>
